package com.android.lovingpet.mine.pet.view;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.android.lovingpet.R;
import com.android.lovingpet.base.BaseFragment;
import com.android.lovingpet.bean.Pet;
import com.android.lovingpet.mine.pet.IPetContract;
import com.android.lovingpet.mine.pet.PetPresenter;
import com.android.lovingpet.util.Utility;
import org.greenrobot.eventbus.EventBus;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
 * Created by ikata on 2018/4/29.
 */

public class PetFragment extends BaseFragment<IPetContract.View, PetPresenter> implements IPetContract.View,View.OnClickListener, PetRvAdapter.OnItemClickListener {

    @BindView(R.id.rv_pet)
    RecyclerView rvPet;
    @BindView(R.id.tb_addPet)
    Toolbar tbAddPet;
    Unbinder unbinder;

    private PetRvAdapter petRvAdapter;
    @Override
    protected int setContentView() {
        return R.layout.fragment_pet;
    }

    @Override
    protected void onCreateView(View view) {
        unbinder= ButterKnife.bind(this,view);
        setTitle(view,"我的宠物");
        tbAddPet.setOnClickListener(this);
        initView();
    }
    private void initView()
    {
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        rvPet.setLayoutManager(linearLayoutManager);
        petRvAdapter=new PetRvAdapter();
        rvPet.setAdapter(petRvAdapter);
        petRvAdapter.setItemClickListener(this);
        //获取宠物已拥有的宠物id
        getPresenter().getPetId(Utility.getRealId(),0,1,10,0);
    }

    @Override
    public PetPresenter createPresenter() {
        return new PetPresenter();
    }

    @Override
    public IPetContract.View createView() {
        return this;
    }

    @Override
    public void next() {
        getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.pet_content, new AddPetFragment()).commit();
    }

    @Override
    public void showMyPet(Pet pet) {
        runOnUiThread(() -> petRvAdapter.addPet(pet));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tb_addPet})
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.tb_addPet:
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.pet_content,new AddPetFragment()).commit();

                break;
        }
    }

    @Override
    public void onItemClick(int position) {
        EventBus.getDefault().postSticky(petRvAdapter.getPet(position));
        getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.pet_content,new PetDetailsFragment(),"petDetails").commit();
    }

}
